package org.jsola.contract.common;

import org.jsola.common.ClassKit;
import org.jsola.core.entity.BaseCreateDO;
import org.jsola.core.entity.BaseTreeDO;
import org.jsola.core.entity.BaseUpdateDO;
import org.jsola.orm.filter.Order;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.List;

/**
 * @author JanusMix
 */
public class ExampleKit {

    /**
     * 设置example的排序
     * @param example example
     * @param orders orders
     */
    public static void setExampleOrder(Example example, List<Order> orders) {
        Class<?> doClass = example.getEntityClass();
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {
                Example.OrderBy orderBy = example.orderBy(order.getProperty());
                if (order.isDesc()) {
                    orderBy.desc();
                } else {
                    orderBy.asc();
                }
            }
        } else {
            // 树形按sort升序
            if (BaseTreeDO.class.isAssignableFrom(doClass)) {
                example.orderBy("sort").asc();
            // 如果有sort字段，升序
            } else if (ClassKit.hasGetMethod(doClass,"sort")) {
                example.orderBy("sort").asc();
            // 按最后更新时间倒序
            } else if (BaseUpdateDO.class.isAssignableFrom(doClass)) {
                example.orderBy("gmtModified").desc();
            // 按创建时间倒序
            } else if (BaseCreateDO.class.isAssignableFrom(doClass)) {
                example.orderBy("gmtCreate").desc();
            } else {
                example.orderBy("id").desc();
            }
        }
    }


}
